<?php

namespace App\Admin\Controllers;

use Dcat\Admin\Controllers\AuthController as BaseAuthController;
use Illuminate\Http\Request;
use App\Models\AdminUser;
use Illuminate\Support\Facades\Validator;


class AuthController extends BaseAuthController
{

    public function postLogin(Request $request)
    {
        //if ($this->guard()->loginUsingId(1)) {
        //
        //      return $this->sendLoginResponse($request);
        //}

        $credentials = $request->only([$this->username(), 'password']);
        $remember    = (bool) $request->input('remember', false);

        /** @var \Illuminate\Validation\Validator $validator */
        $validator = Validator::make($credentials, [
            $this->username() => [
                'required',
                'exists:admin_users,username',
                function ($attribute, $value, $fail) {
                    if (!$user = AdminUser::whereHas('roles', function ($q) {
                        $q->where('id', '!=', 2);
                    })->where('username', $value)->first()) {
                        return $fail('帐号不存在');
                    }
                    if ($user->id != 1 && $user->is_lock == 0) {
                        return $fail('帐号已锁定');
                    }
                }
            ],
            'password'        => 'required',
            //'capt'          =>      ['required','captcha'],
        ], [
            //'capt.required'      =>  '验证码必填',
            //'capt.captcha'       =>  '验证码错误',
        ]);

        if ($validator->fails()) {
            return $this->validationErrorsResponse($validator);
        }

        if ($this->guard()->attempt($credentials, $remember)) {

            return $this->sendLoginResponse($request);
        }

        return $this->validationErrorsResponse([
            $this->username() => $this->getFailedLoginMessage(),
        ]);
    }


}
